<!--点击子任务跳转后的流程图页面组件-->
<template>
  <CCard class="childtask">
    <div class="btns">
      <div
        style="
          margin-top: 10px;
          width: 76vh;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        "
      >
        <span class="headerFont" :title="taskName">
          <img
            @click="goBack"
            src="@/assets/icons/goback.svg"
            alt
            class="goBtn"
          />
          {{ taskName }}流程
        </span>
        <!-- <CButton class="callback btn_style" @click="goBack">
                                  <CIcon name="cil-chevron-circle-left-alt" />&nbsp;返回
        </CButton>-->
      </div>

      <div>
        <!-- <CButton class="btn_style" @click="xmlType=true;getXML()" data-permission="Btn_TaskCenter_Refresh">
                  <img src="@/assets/icons/update.svg" class="imgstyle" alt />
                  刷新
        </CButton>-->
        <CButton
          class="btn_style system-btn-style"
          id="restartId"
          color="info"
          @click="updateStatusFromdon('retry')"
          data-permission="Btn_TaskCenter_Retry"
        >
          <img
            src="@/assets/icons/restart.svg"
            class="imgstyle"
            alt
          />&nbsp;节点重试
        </CButton>
        <CButton
          class="btn_style system-btn-style"
          id="restartId"
          color="info"
          @click="updateStatus('retry')"
          data-permission="Btn_TaskCenter_Retry"
        >
          <img
            src="@/assets/icons/restart.svg"
            class="imgstyle"
            alt
          />&nbsp;错误重试
        </CButton>
        <!--  <CButton
          class="btn_style system-btn-style"
          color="info"
          @click="pauseAndResume"
          data-permission="Btn_TaskCenter_Pause"
        >
          <span v-show="pause" id="zanting">
            <img
              src="@/assets/icons/pause.svg"
              class="imgstyle"
              alt
            />&nbsp;暂停 &nbsp;
          </span>
          <span v-show="recovery">
            <img
              src="@/assets/icons/retry.svg"
              class="imgstyle"
              alt
            />&nbsp;恢复
          </span>
        </CButton>-->
        <CButton
          class="btn_style system-btn-style"
          @click="updateStatus('stop')"
          id="zhongzhi"
          color="info"
          data-permission="Btn_TaskCenter_Ter"
        >
          <img src="../../assets/icons/stop.svg" class="imgstyle" alt />
          &nbsp;&nbsp;终止
        </CButton>
        <CButton
          class="btn_style system-btn-style"
          id="restartId"
          color="info"
          @click="updateStatus('restart')"
          data-permission="Btn_TaskCenter_Restar"
        >
          <img
            src="@/assets/icons/start.svg"
            alt
            class="imgstyle"
          />&nbsp;&nbsp;重启
        </CButton>
        <!-- //data-permission="Btn_ProcessFlow_UpP"-->
        <CButton
          class="btn_style system-btn-style"
          id="restartId"
          color="info"
          @click="goToWorkflowById()"
          data-permission="Btn_check_liucheng"
        >
          <img
            src="@/assets/icons/start.svg"
            alt
            class="imgstyle"
          />&nbsp;&nbsp;查看流程
        </CButton>

        <!-- <CButton class="journal btn_style" @click="xmlType=true;getXML()">
        <img src="@/assets/icons/刷新.svg" alt />-->
        <!-- <img src="@/assets/icons/update.png" alt/> -->
        <!-- <CIcon name="cil-bug" />&nbsp; -->
        <!-- 刷新
        </CButton>-->
        <!-- <CButton class="restart btn_style" id="restartId" @click="updateStatus('retry')">
                          <img src="@/assets/icons/retry.png" alt />&nbsp;重试
                        </CButton>
                        <CButton class="suspend btn_style" @click="pauseAndResume">
                          <span v-show="pause" id="zanting">
                            <CIcon name="cil-media-pause" />&nbsp;暂停 &nbsp;
                          </span>
                          <span v-show="recovery">
                            <CIcon name="cil-caret-right" id="qidong" />&nbsp;恢复
                          </span>
                        </CButton>
                        <CButton class="ended btn_style" @click="updateStatus('stop')" id="zhongzhi">
                          <img src="../../assets/icons/stop.png" alt />
                          &nbsp;&nbsp;终止
                        </CButton>
                        <CButton class="restart btn_style" id="restartId" @click="updateStatus('restart')">
                          <CIcon name="cil-power-standby" />&nbsp;&nbsp;重启
        </CButton>-->
      </div>

      <div style class="legendBox">
        <!--图例@start-->
        <div class="legendCon">
          <ul>
            <li>
              <em style="background: #67b9a5"></em>
              <span>成功</span>
            </li>
            <li>
              <em style="background: #c11113"></em>
              <span>失败</span>
            </li>
            <li title="部分失败">
              <em style="background: #ffab3f"></em>
              <span>警告</span>
            </li>
            <li>
              <em style="background: #b0b4b9"></em>
              <span>待执行</span>
            </li>
            <li>
              <em style="background: #4d7bd7"></em>
              <span>执行中</span>
            </li>
            <li>
              <em style="background: #522fdc"></em>
              <span>跳过</span>
            </li>
          </ul>
        </div>
        <!--图例@end-->
      </div>
    </div>

    <CModal
      size="lg"
      class="bglogbody"
      title="任务日志"
      color="info"
      :show.sync="warningModal"
      :closeOnBackdrop="false"
      centered
    >
      <div v-for="(item, index) in logList" :key="index" class>
        {{ item.logConsole }}
      </div>
      <template #footer class="footerBtns">
        <CButton @click="close" color="info" id="ok" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </CModal>

    <div v-show="modal2" class="imgCard">
      <CCard>
        <CCardBody>
          <div
            :style="
              'width:100%;height:calc(' +
              iframeHeight +
              'px - 170px);overflow: auto'
            "
          >
            <iframe
              style="width: 100%; height: 5350px; border: 0"
              src="about:blank"
              ref="mainIframe"
              name="mainIframe"
              id="mainIframe"
            ></iframe>
          </div>
        </CCardBody>
      </CCard>
    </div>

    <TaskDetailsChild
      v-show="Tasklist"
      class="rightNav"
      :taskId="childTaskId"
      :workflowId="startWorkflowId"
    ></TaskDetailsChild>

    <!-- <mapCompereDetal ref="mapCompereDetal" style="width: 100%; height: 100%">
    </mapCompereDetal> -->
  </CCard>
</template>
<!--js代码-->
<script>
import TaskDetailsChild from "@/views/taskMonitor/taskDetailsChild";
import mapCompereDetal from "./common/mapCompereDetal";

export default {
  name: "taskDetails",
  data() {
    return {
      templateId: "",
      xmlType: false,
      iframeHeight: 0,
      Tasklist: false,
      logList: [],
      modal2: false,
      data: [],
      picture: "",
      workflowId: "",
      pause: true,
      recovery: false,
      xmlContent: "",
      childTaskId: "",
      warningModal: false,

      logConsole: [],
      taskName: "",
    };
  },
  components: {
    TaskDetailsChild,
    mapCompereDetal,
  },
  created() {
    this.workflowId = this.$route.params.id;
    this.startWorkflowId = this.$route.params.startId;
    this.status = this.$route.params.status;

    this.taskName = this.$route.params.taskName;
    this.getXML();
  },
  mounted() {
    this.getStatus();
    this.iframeHeight = window.document.body.offsetHeight;
    const _this = this;
    window.addEventListener(
      "resize",
      function () {
        _this.iframeHeight = window.document.body.offsetHeight;
      },
      false
    );
    this.$nextTick(function () {
      this.GlobalPermissionRender.render();
    });
  },
  methods: {
    iframe() {
      // iframe 传参
      let self = this;
      const mapFrame = this.$refs["mainIframe"];
      let userIdFromLocalStorage = "0";

      try {
        let user = JSON.parse(window.sessionStorage.getItem("vuex")).user;
        if (user != null) {
          userIdFromLocalStorage = user.userId;
        }
      } catch (e) {
        console.error("User information get failed");
      }
      mapFrame.src =
        "workflow/index.html?id=" +
        this.startWorkflowId +
        "&mode=monitor" +
        "&userId=" +
        userIdFromLocalStorage;
      window["show"] = (type, taskId) => {
        self.showTasklist(type, taskId);
      };

      window["doubleClick"] = (type, taskId, algId, algoType) => {
        self.doubleClick(type, taskId, algId, algoType);
      };
      return;
    },
    goToWorkflowById() {
      String.prototype.replaceAll = function (s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
      };

      this.$router.push({
        path: `/updateWorkflow/${this.templateId}`,
        query: {
          from: "taskDetails",
          id: this.workflowId,
          status: this.status,
          taskName: `${this.taskName.replaceAll("/", "*")}`,
          taskCode: this.startWorkflowId,
        },
      });
    },
    showTasklist(type, taskId) {
      this.Tasklist = type;
      if (type) {
        this.childTaskId = taskId;
      }
    },
    // 任务监控算法双击事件
    doubleClick(type, taskId, algId, algoType) {
      let myToken = window.sessionStorage.getItem("PIECloud-Token");
      // 人机交互双击打开客户端
      if (algoType === "HumanTask") {
        let url = "";
        // 启动人工交互客户端
        if (algId == "piesat.humantask.measure") {
          //点位量测
          url = "imageinteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.drafting") {
          //专题制图
          url = "CartoInteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.sampling") {
          //参量样本选择
          url = "classifiedinteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.check") {
          //人工质检
          url = "checkinteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.mosaic") {
          // 影像镶嵌
          url = "MosaicInteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.qamodel") {
          //  产品质量分析模块
          url = "QAModelInteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.spatial") {
          //  空间分析与制图
          url = "SpatialInteractive://" + myToken + "/" + taskId + "/";
        } else if (algId == "piesat.humantask.dataloader") {
          //  数据加载
          url = "DataLoaderInteractive://" + myToken + "/" + taskId + "/";
        } else if (algId.includes("piesat.humantask")) {
          let name = algId.split(".")[2];
          url = name + "Interactive://" + myToken + "/" + taskId + "/";
        }
        if (url == "") return;
        window.location.href = url;
      }
    },

    warningModalShow() {
      this.warningModal = !this.warningModal;
      this.getLog();
    },
    //日志
    getLog() {
      let self = this;
      let path =
        self.$api.taskManageApi.loglist +
        "?flowId=" +
        self.startWorkflowId +
        "&pageSize=10000&page=1";
      this.http.get(path).then((res) => {
        if (res.data.code === 0) {
          let logData = res.data.data.log;
          let newlogArr = [];
          for (let i = 0; i < logData.length; i++) {
            let log = {};
            let dataContent = logData[i].content;
            let dataTime = logData[i].time;
            var dateee = new Date(dataTime).toJSON();
            let newDate = new Date(+new Date(dateee) + 8 * 3600 * 1000)
              .toISOString()
              .replace(/T/g, " ")
              .replace(/\.[\d]{3}Z/, "");

            log.logConsole = newDate + "\xa0\xa0\xa0\xa0" + dataContent;
            log.time = logData[i].time;
            newlogArr.push(log);
          }
          this.logConsole = newlogArr;
          self.logList = newlogArr;
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    getStatus() {
      if (this.status == 2) {
        this.recovery = true;
        this.pause = !this.recovery;
      }
    },
    pauseAndResume() {
      if (this.pause == true) {
        this.updateStatus("paused");
      } else {
        this.updateStatus("resume");
      }
    },
    //工作流的五个状态按钮
    updateStatus(status) {
      let id = this.startWorkflowId;
      let path =
        this.$api.taskManageApi.taskDetailsUpdateStatus + id + "/" + status;

      let param = {
        _loadingContainer: document.querySelector(".c-main"),
      };

      this.http.put(path, param).then((res) => {
        if (res.data.code == 0) {
          if (status === "paused") {
            this.recovery = true;
            this.pause = false;
          } else if (status === "resume") {
            this.pause = true;
            this.recovery = false;
          }
          this.$Message.success(res.data.message);
          this.getFlowStatus();
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    updateStatusFromdon() {
      if (this.childTaskId === "") {
        this.$Message.error("请选择节点！");
        return;
      }
      if (this.childTaskId === "undefined") {
        this.$Message.error("请选择已运行节点！");
        return;
      }
      let params = {
        reRunFromTaskId: this.childTaskId,
        reRunFromWorkflowId: this.startWorkflowId,
      };
      this.http
        .post(this.$api.taskManageApi.reRunWorkflow, params)
        .then((res) => {
          if (res.status === 200) {
            this.$Message.success("重试成功！");
          } else {
            this.$Message.error(res.data.message);
          }
        })
        .catch((err) => {
          this.$Message.error(err);
        });
    },
    getFlowStatus() {
      let startWorkflowId = this.startWorkflowId;
      let path =
        this.$api.taskManageApi.queryInfoByWorkFlowId + startWorkflowId;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.status == 2) {
            this.recovery = true;
            this.pause = !this.recovery;
          } else {
            this.pause = true;
            this.recovery = !this.pause;
          }
        }
      });
    },
    getXML() {
      // xml带状态码
      let self = this;
      let path =
        this.$api.taskManageApi.childTaskWorkFlow +
        this.startWorkflowId +
        "/running";
      let params = {
        format: "xml",
      };

      this.http.get(path, params).then((res) => {
        if (res.data.code === 0) {
          this.xmlContent = res.data.data;
          this.templateId = res.data.templateId;
          this.modal2 = true;
          self.iframe();
        }
      });
    },

    //关闭任务日志弹窗
    close() {
      this.warningModal = false;
    },
  },
};
</script>
<!--css样式-->
<style scoped>
.card-body {
  padding: 0;
}
.btns {
  display: flex;
  border-bottom: 1px solid #d8d8d8;
  justify-content: space-between;
  padding: 25px 14px;
}

.journal {
  margin-left: 200px;
  background-color: #3399ff;
  color: white;
  width: 140px;
  height: 35px;
}

.callback {
  margin-left: 2px;
}
.restart {
  margin-right: 0px;
}

.createTaskImg {
  margin-left: 180px;
  width: 50%;
  height: 85%;
}

.c-icon {
  margin-bottom: 7px;
}
.rightNav {
  position: absolute;
  right: 0px;
  top: 70px;
}

.btn_style {
  border-radius: 4px;
  width: 90px;
  height: 32px;
  margin-left: 10px;
  margin-top: 5px;
  padding: 5px;
}
.childtask {
  height: 100%;
}
.card {
  height: 100%;
  margin-bottom: 0 !important;
  border: 0;
  border-radius: 0;
}
.bglogbody .modal-body {
  overflow: scroll;
}

/*图例@start*/
.legendBox {
  position: absolute;
  left: 30px;
  top: 121px;
}
.legendBox .legendCon {
  position: absolute;
  width: 125px;
  background: rgba(255, 255, 255, 0.5);
  z-index: 100;
  border-radius: 3px;
  border: none;
}
.legendBox .legendCon ul {
  padding-left: 0;
  margin-top: 5px;
  margin-bottom: 5px;
}

.legendBox .legendCon ul li {
  list-style-type: none;
  line-height: 24px;
  color: rgba(0, 0, 0, 0.8);
  padding-left: 15px;
  font-size: 12px;
}
.legendBox .legendCon ul li em {
  width: 40px;
  height: 10px;
  line-height: 10px;
  margin-right: 15px;
  border-radius: 3px;
}

.legendBox .legendCon ul li em,
.legendBox .legendCon ul li span {
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
}
/*图例@end*/
.headerFont {
  font-size: 18px;
  margin-top: 3px;
}
.goBtn {
  width: 25px;
  height: 25px;
  margin-top: -2px;
  margin-right: 7px;
}
.imgstyle {
  width: 16px;
  height: 16px;
  margin-top: -5px;
  padding-top: 2px;
}
</style>
